<?php

class MultiLevelCategoriesController extends Controller {
    public $layout = 'contents';
    const PAGE_SIZE = 100;

    /**
     * @var CActiveRecord the currently loaded data model instance.
     */
    private $_model;

    /**
     * @return array action filters
     */
    public function filters() {
        return array(
            'accessControl', // perform access control for CRUD operations
        );
    }

    /**
     * Specifies the access control rules.
     * This method is used by the 'accessControl' filter.
     * @return array access control rules
     */
    public function accessRules() {
        return array(
            array('allow',  // allow all users to perform 'index' actions
                'actions' => array('index'),
                'users' => array('*'),
            ),
            array('allow', // allow authenticated user to perform 'create' and 'update' actions
                'actions' => array('create', 'update', 'generateJsFile'),
                'users' => array('@'),
            ),
            array('allow', // allow admin user to perform 'admin' and 'delete' actions
                'actions'=>array('delete'),
                'users'=>array('admin'),
            ),
            array('deny',  // deny all users
                'users'=>array('*'),
            ),
        );
    }

    /**
     * Creates a new model.
     * If creation is successful, the browser will be redirected to the 'index' page.
     */
    public function actionCreate() {
        $model = new MultiLevelCategory;
        if (isset($_POST['MultiLevelCategory'])) {
            $model->attributes = $_POST['MultiLevelCategory'];
            if ($model->save()) {
                $this->redirect(array('index'));
            }
        }

        $this->render('edit', array(
            'model'=>$model,
        ));
    }

    /**
     * Updates a particular model.
     * If update is successful, the browser will be redirected to the 'index' page.
     */
    public function actionUpdate() {
        $model = $this->loadModel();
        if (isset($_POST['MultiLevelCategory'])) {
            if ($_POST['MultiLevelCategory']['id'] == $_POST['MultiLevelCategory']['parent_id']) {
                $model->addError('parent_id', Yii::t('multiLevelCategory', 'parent_can_not_self'));
            } else {
                $model->attributes = $_POST['MultiLevelCategory'];
                if ($model->save()) {
                    $this->redirect(array('index', 'node' => $_POST['MultiLevelCategory']['parent']));
                }
            }
        }

        $this->render('edit', array(
            'model' => $model,
        ));
    }

    /**
     * Deletes all secected model.
     * If deletion is successful, the browser will be redirected to the 'index' page.
     */
    public function actionDelete() {
        if (Yii::app()->request->isPostRequest) {
            $delete = Yii::app()->request->getPost('delete');
            foreach ($delete as $id) {
                MultiLevelCategory::model()->findByPk($id)->delete();
            }

            $this->redirect(array('index', 'parent' => Yii::app()->request->getParam('parent')));
        } else {
            throw new CHttpException(400, 'Invalid request. Please do not repeat this request again.');
        }
    }

    // generate JavaScript file
    // path: /root/meida/datas/MultiLevelCategorys.js
    public function actionGenerateJsFile() {
        if (Yii::app()->request->isPostRequest) {
            ini_set("memory_limit", "-1");
            set_time_limit(0);

            $categories = MultiLevelCategory::model()->findAll(array(
                'condition' => 'parent_id = 1',
                'select' => 'id',
            ));
            foreach ($categories as $n => $category) {
                $fp = fopen("media/datas/mlc_{$category->id}.js", 'w+');
//                $this->_js = '';
                if ($n >= 1) {
                    $this->_js = 'var items = new Array(';
                }
                $js = $this->getJsContent($category->id);
                fwrite($fp, $js);
                fclose($fp);
            }
            
            Yii::app()->user->setFlash('generateJsFileSucceed', '生成“多级分类”JaveScript 文件成功。');
        }

        $this->render('generateJsFile');
    }

    // 写入 js 文件
    private $_js = 'var items = new Array(';
    private function getJsContent($parent) {
        $criteria = new CDbCriteria();
        $criteria->condition = "parent_id = {$parent}";
        $criteria->select = array('id', 'name', 'pinyin', 'level');
        $criteria->order = 'pinyin ASC';
        $roots = MultiLevelCategory::model()->findAll($criteria);
        foreach ($roots as $root) {
            $this->_js .= "[{$root->level},\"{$root->pinyin}、{$root->name}\",\"{$root->id}\"],";
            if (MultiLevelCategory::hasChild($root->id)) {
                $this->getJsContent($root->id);
            }
        }
        $this->_js = mb_substr($this->_js, 0, mb_strlen($this->_js, 'utf-8') - 1, 'utf-8');
        
        return $this->_js .= ');';
    }

    /**
     * Lists all models.
     */
    public function actionIndex() {
        $parent = Yii::app()->request->getParam('parent', 1);
        $criteria = new CDbCriteria;
        $criteria->condition = "parent_id = {$parent}";

        $pages = new CPagination(MultiLevelCategory::model()->count($criteria));
        $pages->pageSize = self::PAGE_SIZE;
        $pages->applyLimit($criteria);
        

        $sort = new CSort('MultiLevelCategory');
        $sort->applyOrder($criteria);

        $roots = MultiLevelCategory::model()->findAll($criteria);
        
        $this->render('index',array(
            'roots' => $roots,
            'pages' => $pages,
            'sort' => $sort,
            'parent' => $parent,
        ));
    }

    /**
     * Returns the data model based on the primary key given in the GET variable.
     * If the data model is not found, an HTTP exception will be raised.
     */
    public function loadModel() {
        if ($this->_model === null) {
            if (isset($_GET['id']))
                $this->_model = MultiLevelCategory::model()->findbyPk($_GET['id']);
            if ($this->_model === null)
                throw new CHttpException(404, 'The requested page does not exist.');
        }
        return $this->_model;
    }
}
